package org.example.day07;

/**
 * 第三章节3.1.5: 代码演示wait/notify机制
 *      注意: ①线程notify后不会释放锁，而是继续执行直到退出同步代码块.
 *           ②最早wait的线程被唤醒，唤醒后不会立即执行，等notify的线程先退出释放锁，该线程才会开始执行。
 */
public class MyThread4 extends Thread{
    private Object lock;

    public MyThread4(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        try {
            synchronized (lock){
                System.out.println("开始 wait time = " + System.currentTimeMillis());
                lock.wait();
                System.out.println("结束 wait time = " + System.currentTimeMillis());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            Object o = new Object();
            MyThread4 m4 = new MyThread4(o);
            m4.start();
            Thread.sleep(3000);
            Thread4A ta = new Thread4A(o);
            ta.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread4A extends Thread{
    private Object lock;

    public Thread4A(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock){
            System.out.println("开始 notify time = " + System.currentTimeMillis());
            lock.notify();
            System.out.println("结束 notify time = " + System.currentTimeMillis());
        }
    }
}